<?php
namespace app\controllers\common;

use yii\web\Controller;
use app\service\UrlService;
use app\models\User;
use app\models\Access;
use app\models\RoleAccess;
use app\models\UserRole;
use app\models\Visitlog;
use yii;
class BaseController extends Controller
{

	protected $auth_cookie_name = 'kervi';
	protected $current_user = '';
	protected $allowAllAction = [
		'error/forbidden',
		'user/login',
		'user/register',
		'user/vlogin',
		'default/index',
	];
	protected $useraccess = [];

	//框架统一的拦截器，（中间件）
	public function beforeAction($action){
		$login_status = $this->checkLoginSatus();
		if(!$login_status && !in_array($action->uniqueId,$this->allowAllAction)){
			if(\yii::$app->request->isAjax){
				$this->renderJSON('[]','未登录',-302);
			}else{
				$this->redirect(UrlService::BuildUrl('/user/login'));
			}
			return false;
		}

		/*  记录访问日志  开启访问日志*/
		// $this->wrilog($action); //开启访问日志

		/* 
			检查权限/
			没有权限则跳转到eror/forbidden页面
		*/
		if(!$this->checkprivilage( $action->getUniqueId() ) ){
			echo $this->render( UrlService::buildUrl('/error/forbidden') );
			die;
		}
		return true;
	}

	public function checkprivilage($url){
		/*
			r如果是超级管理员，不用检查
			r如果在不用登陆的页面也不用检查
			r检查权限再不行允许访问的范围里
		*/
		if($this->current_user && $this->current_user['is_admin']){
			return true;
		}
		if(in_array($url,$this->allowAllAction)){
			return true;
		}
		return in_array($url,$this->getRolePriviage());
	}
	/*  
		获取用户权限
		o.根据用户id获取用户的角色
		0.根据角色id获取对应的权限
		@return  array 
	*/
	public function getRolePriviage( $uid = 0 ){
		if($uid){
			$Roles = UserRole::find()->where(['uid'=>$uid])->select('rid')->asArray()->column();
		}else{
			$Roles = UserRole::find()->where(['uid'=>$this->current_user['id']])->select('rid')->asArray()->column();

		}
		
		//角色的权限
		$role_access = RoleAccess::find()->where(['rid'=>$Roles])->select('accid')->asArray()->column();
		if($role_access){
			$access = Access::find()->where(['id'=>$role_access])->select('urls')->asArray()->column();
			// 遍历解码
			if($access){
				foreach ($access as $key => $value) {
					$a = json_decode($value,1);
					$this->useraccess = array_merge($this->useraccess,$a);
				}
			}
		}
		return $this->useraccess;
	}


	/* 验证登录状态是否有效， 返回true 或 false  */

	public function checkLoginSatus(){
		$request = \Yii::$app->request;
		$cookie = $request->cookies;
		$auth_cookie = $cookie->get($this->auth_cookie_name);
		if(!$auth_cookie){
			return false;
		}
		// 吧分割后的数组赋值给 $auth_token和 $uid
		list($auth_token,$uid) = explode('#',$auth_cookie);

		if(!$auth_token || !$uid){
			return false;
		}
		/* 正则验证，是不是数字，，， */
		if($uid && preg_match("/^\d+$/",$uid)){
			$userinfo = User::find()->where(['id'=>$uid])->select(['id','name','email','status','is_admin'])->one();
			if(!$userinfo)return false;
			if( $auth_token != $this->createAuthToken($userinfo['name'],$userinfo['email'],$_SERVER['HTTP_USER_AGENT']) ) {
					return false;
			}
			$this->current_user = $userinfo;
			$view = \yii::$app->view;
			$view->params['current_user'] = $userinfo;

			return true;
		}
		return false;
	}
	/* 设置登录状态的cookie*/
	public function createLoginStatues($user_info=[]){
        $user_auth_token = $this->createAuthToken($user_info['name'],$user_info['email'],$_SERVER['HTTP_USER_AGENT']);
        $cookie_target = \Yii::$app->response->cookies;
		$cookie_target->add(new \yii\web\cookie([
			'name'=>'kervi',
			'value'=>$user_auth_token.'#'.$user_info['id'],
		]));

	}
	/*  用户信息相关的校验码函数  */
	public function createAuthToken($name,$email,$user_agent){
		return md5($name.$email.$user_agent);
	}

/* yii的 获取get请求参数 */
	public static function get($key,$default=''){
		return \Yii::$app->request->get($key,$default);
	}

	public static function post($key,$default=''){
		return Yii::$app->request->post($key,$default);
	}

	public function renderJSON($data,$msg='success',$code='200'){
		header('Content-type:application/json');
		echo json_encode( [
			'code'=>$code,
			'data'=>$data,
			'msg'=>$msg,
			'time'=>time(),
		] );

		return Yii::$app->end();//终止请求直接返回;
	}
    public function returnJSON($data,$msg='success',$code='200'){
        header('Content-type:application/json');
        return json_encode( [
            'code'=>$code,
            'data'=>$data,
            'msg'=>$msg,
            'time'=>time(),
        ] );
    }
	//检查redis数据过期时间

    public function keyexpireat($key){
	    if(empty($key)){return 'key is null';}
	    return yii::$app->redis->pttl($key);
    }

    /* 获取原试卷的答案
     *@paperinfo  试卷内容，从数据库取出来之后要解析json，再传过来，这里不做解析操作
     *@return   返回答案数组  （包括单选，多选，判断）
     * 返回类型如下示例
       [  'radio' =>
            array (size=1)
              0 => string 'C' (length=1)
          'checkbox' =>
            array (size=2)
              0 => string 'A&B' (length=3)
              1 => string 'A&B&C' (length=5)
          'judge' =>
            array (size=3)
              0 => string '1' (length=1)
              1 => string '1' (length=1)
              2 => string '1' (length=1)
      ]
     * */
    public function getanswer($paperinfo){
        $result = [];
        foreach($paperinfo as $key => $value){
            if($key == 'completion' || $key == 'boss')continue;
            $result[$key] = [];//初始化一个位置
            foreach($value as $k=>$v){
                $key == 'judge' ? $result[$key][]=$v['is_true'] : $result[$key][]=$v['answer'];
            }
        }

        return $result;
    }

    /*  添加权限，
     *
     * @var $uid 用户ID
     * @var $rid 角色ID
     *
     * */
    public function addRole($uid,$rid){
        $create_time = date('Y-m-d H:i:s');//设置默认值
        if(!is_numeric($uid) || !is_numeric($rid)){ //判断传过来的值是否为数字
            return 500;
        }
        if( UserRole::findOne(['uid'=>$uid,'rid'=>$rid]) ){ //判断数据是否存在
            return 501;
        }
        $userRole = new UserRole();
        $userRole->uid = $uid;
        $userRole->rid = $rid;
        $userRole->create_time = $create_time;
        $userRole->save();
        return 200;
    }
    //用户操作日志记录方法
    public function wrilog($action){
		$paramget = $this->get( null );
		$parampost = $this->post( null );
	
		$Visitlog = new Visitlog();
		$Visitlog->uid = $this->current_user ? $this->current_user['id'] : 0 ;
		$Visitlog->name = $this->current_user ? $this->current_user['name'] : '';
		$Visitlog->url = $action->getUniqueId();
		$Visitlog->request_params = json_encode(array_merge($paramget,$parampost));
		$Visitlog->ua = isset( $_SERVER['HTTP_USER_AGENT'] )?$_SERVER['HTTP_USER_AGENT']:'';
		$Visitlog->ip = isset( $_SERVER['REMOTE_ADDR'] )?$_SERVER['REMOTE_ADDR']:'';
		$Visitlog->create_time = date('Y-m-d H:i:s');
		$Visitlog->save();
    }
}